/**
 * @function 微信接口调用
 * @description 如果是GET方法 处理url和参数后输出
 */

import { messageFileProps } from 'miniprogram/miniprogram_npm/@vant/weapp/uploader/shared';
import msg from '../msg';
import {Parameter} from './interface';
import {getInterfaceRoute} from './route';

function getParamsToUrl(param: Parameter, url: string): string {
  // 判空
  if (param.url.length == 0) {
    return url;
  }
  Object.keys(param.data).forEach((key: string) => {
    url += `&${key}=${param.data[key]}`;
  })
  console.log('[tools.ts-getParamsToUrl()]', url);
  return url;
}

export async function request(param: Parameter): Promise<WechatMiniprogram.RequestSuccessCallbackResult<string | Record<string, any> | ArrayBuffer>> {
  return new Promise((resolve, reject) => {
    if(param.method == 'GET') {
      param.url = getParamsToUrl(param, getInterfaceRoute(param.url));
      param.data = {};
    }
    wx.request({
      url: param.url,
      method: param.method,
      header: {
        'content-type': 'application/json'
      },
      data: param.data,
      success: (res:any) => {
        if(!res.data.code){
          msg.show('系统维护中','请稍后再试');
        }
        resolve(res);
      },
      fail: err => {
        console.log('发生了错误')
        reject(err);
      }
    })
  })
}